<template>
  <div class="todo-container">
    <h1 class="title">待办事项</h1>
    <div class="input-container">
      <input
        v-model="newTodo"
        type="text"
        placeholder="添加新的待办事项"
        @keyup.enter="addTodo"
        class="main-input"
      >
      <button @click="addTodo" class="btn add-btn">添加</button>
      <button @click="deleteAll" class="btn delete-all-btn">删除全部</button>
    </div>
    <ul class="todo-list">
      <li v-for="todo in todos" :key="todo.id" class="todo-item">
        <span class="bullet">•</span>
        <div v-if="editingId === todo.id" class="edit-container">
          <input
            v-model="editingText"
            type="text"
            @keyup.enter="saveEdit(todo)"
            @blur="saveEdit(todo)"
            ref="editInput"
            class="edit-input"
          >
          <button @click="saveEdit(todo)" class="btn save-btn">保存</button>
        </div>
        <div v-else class="todo-content">
          <span class="todo-text">{{ todo.title }}</span>
          <div class="todo-actions">
            <button @click="startEdit(todo)" class="icon-btn edit-btn">
              <span class="edit-icon">✎</span>
            </button>
            <button @click="deleteTodo(todo.id)" class="icon-btn delete-btn">
              <span class="delete-icon">🗑</span>
            </button>
          </div>
        </div>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import axios from 'axios';

const todos = ref([]);
const newTodo = ref('');
const editingId = ref(null);
const editingText = ref('');
const editInput = ref(null);

const fetchTodos = async () => {
  try {
    const response = await axios.get('http://localhost:3000/todos', {
      headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    });
    todos.value = response.data;
  } catch (error) {
    console.error('获取待办事项失败:', error);
    alert('获取待办事项失败，请重试。');
  }
};

const addTodo = async () => {
  if (!newTodo.value.trim()) return;
  try {
    const response = await axios.post('http://localhost:3000/todos',
      { title: newTodo.value },
      { headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } }
    );
    todos.value.push(response.data);
    newTodo.value = '';
  } catch (error) {
    console.error('添加待办事项失败:', error);
    alert('添加待办事项失败，请重试。');
  }
};

const startEdit = (todo) => {
  editingId.value = todo.id;
  editingText.value = todo.title;
  nextTick(() => {
    editInput.value?.focus();
  });
};

const saveEdit = async (todo) => {
  if (editingId.value !== todo.id) return;
  try {
    await axios.put(`http://localhost:3000/todos/${todo.id}`,
      { title: editingText.value, completed: todo.completed },
      { headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } }
    );
    todo.title = editingText.value;
    editingId.value = null;
  } catch (error) {
    console.error('更新待办事项失败:', error);
    alert('更新待办事项失败，请重试。');
  }
};

const deleteTodo = async (id) => {
  try {
    await axios.delete(`http://localhost:3000/todos/${id}`, {
      headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    });
    todos.value = todos.value.filter(todo => todo.id !== id);
  } catch (error) {
    console.error('删除待办事项失败:', error);
    alert('删除待办事项失败，请重试。');
  }
};

const deleteAll = async () => {
  if (!confirm('确定要删除所有待办事项吗？')) return;
  try {
    await Promise.all(todos.value.map(todo =>
      axios.delete(`http://localhost:3000/todos/${todo.id}`, {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
      })
    ));
    todos.value = [];
  } catch (error) {
    console.error('删除所有待办事项失败:', error);
    alert('删除所有待办事项失败，请重试。');
  }
};

onMounted(fetchTodos);
</script>

<style scoped>
.todo-container {
  max-width: 600px;
  margin: 2rem auto;
  padding: 2rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 2.5rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 2rem;
  text-align: center;
}

.input-container {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 2rem;
}

.main-input {
  flex: 1;
  padding: 0.75rem 1rem;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  outline: none;
  transition: border-color 0.3s;
}

.main-input:focus {
  border-color: #666;
}

.btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.3s;
}

.add-btn {
  background-color: #4A90E2;
  color: white;
}

.add-btn:hover {
  background-color: #357ABD;
}

.delete-all-btn {
  background-color: #E74C3C;
  color: white;
}

.delete-all-btn:hover {
  background-color: #C0392B;
}

.todo-list {
  list-style: none;
  padding: 0;
}

.todo-item {
  display: flex;
  align-items: center;
  padding: 1rem 0;
  border-bottom: 1px solid #eee;
  gap: 0.5rem;
}

.bullet {
  font-size: 1.5rem;
  color: #666;
  margin-right: 0.5rem;
}

.todo-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex: 1;
}

.todo-text {
  font-size: 1rem;
  color: #333;
}

.todo-actions {
  display: flex;
  gap: 0.5rem;
}

.icon-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.25rem;
  opacity: 0.6;
  transition: opacity 0.3s;
}

.icon-btn:hover {
  opacity: 1;
}

.edit-icon, .delete-icon {
  font-size: 1.2rem;
}

.edit-container {
  display: flex;
  gap: 0.5rem;
  flex: 1;
}

.edit-input {
  flex: 1;
  padding: 0.5rem;
  border: 2px solid #4A90E2;
  border-radius: 4px;
  font-size: 1rem;
  outline: none;
}

.save-btn {
  background-color: #ffffff;
  color: rgb(0, 0, 0);
}

.save-btn:hover {
  background-color: #c2e6ff;
}
</style>
